<?php

!defined('IN_NOVA') && exit('Access Denied!');

// URL 组装
// 动态模式
// http://www.xklog.org/index.php?m=guestbook&p=1
// Rewrite 模式、全静态模式
// http://www.xklog.org/guestbook/1.html
function U( $url, $module, $params = '', $extra = '' ) {
	global $cache;
	if( $cache->config['arttype'] == '动态' ) {
		$url =  $url . 'index.php?m=' . $module;
		if( $params != '' ) {
			$url =  $url . '&p=' . $params;
			if( is_array( $extra ) ) {
				foreach( $extra as $key => $value ) {
					$url = $url . '&' . $key . '=' . $value;
				}
			}
		}
	} else {
		$url =  $url . $module;
		if( $params != '' ) {
			$url =  $url . '/' . $params;
			if( is_array( $extra ) ) {
		       	foreach( $extra as $key => $value ) {
		    		$url = $url . '/' . $key . '_' . $value;
		    	}
			}
		}
		$url .= '.html';
	}
	return $url;
}

// URL 解析
function _U() {
	global $request;
	if( $request->get( 'm' ) != NULL ) {
		return;
	}
	$url = $request->get( 'URL', 'G', 'array' );
	switch( count( $url ) ) {
	case 1:
		if( $url[0] == '' ) {
			break;
		}
		$temp = substr ( $url[0], 0, strrpos ( $url[0], '.' ) );
		if( $temp == '' ) {
			$request->m = 'err_404';
			break;
		}
		$request->m = $temp;
		break;
	case 2:
		if( $url[0] == '' ) {
			$request->m = 'err_404';
			break;
		}
		$temp = substr ( $url[1], 0, strrpos ( $url[1], '.' ) );
		if( $temp == '' ) {
			$request->m = 'err_404';
			break;
		}
		$request->m = $url[0];
		$request->p = $temp;
		break;
	default:
		if( $url[0] == '' || $url[1] == '' ) {
			$request->m = 'err_404';
			break;
		}
		$request->m = $url[0];
		$request->p = $url[1];
		for( $i = 2 ; $i < count( $url ) ; $i ++ ) {
			if( $url[$i] == '' ) {
				$request->m = 'err_404';
				break;
			}
			if( $i == count( $url ) - 1 ) {
				$url[$i] = substr( $url[$i], 0, strrpos ( $url[$i], '.' ) );
			}
			$temp = explode( '_', $url[$i], 2 );
			if( count( $temp ) != 2 || $temp[0] == '' || $temp[1] == '' ) {
				$request->extra = $url[$i];
			} else {
				$request->$temp[0] = $temp[1];
			}
		}
		break;
	}
}

// 语言读取
function L( $index ) {
	global $_LANGUAGE;
	//[DEBUG]
	global $log;
	//[/DEBUG]
	if( isset( $_LANGUAGE[$index] ) ) {
		return $_LANGUAGE[$index];
	} else {
		//[DEBUG]
		if( defined( 'APP_DEBUG' ) && APP_DEBUG === TRUE ) {
			$log->add( '试图使用未定义的语言包索引：' . $index, E_WARNING );
		}
		//[/DEBUG]
		return $index;
	}
}

// 语言侦测
function check_language() {
	if( !defined( 'APP_LANGAUTO' ) || APP_LANGAUTO == FALSE ) {
		// 不开启语言侦测功能，返回默认
		return APP_LANG;
	}
    // 启用语言侦测功能
	if( isset( $_GET['language'] ) ) {
		// 优先从 GET、POST 中获取语言设置
		$app_path = str_replace( ' ','%20', APP_PATH );
		setcookie( APP_PREFIX . 'language', $_GET['language'], PHP_TIME + 31536000, $app_path );
		return $_GET['language'];
	} elseif( isset( $_COOKIE[APP_PREFIX . 'language'] ) ) {
		// 从 COOKIE 中获取上次用户的选择
		return $_COOKIE[APP_PREFIX . 'language'];
	} elseif( isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) {
		// 自动侦测浏览器语言
		preg_match( '/^([a-z\-]+)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches );
		$app_path = str_replace( ' ','%20', APP_PATH );
		setcookie( APP_PREFIX . 'language', $matches[1], PHP_TIME + 31536000, $app_path );
		return $matches[1];
	} else {
		return APP_LANG;
	}
}

// 连接缓存
function connect_cache( $type = 'VOID', $options = '' ) {
	$cache_class = strtolower( trim( $type ) );
	$cache_path = NOVA_CORE . 'cache/' . $cache_class . '.class.php';
	if( is_file( $cache_path ) ) {
		include( $cache_path );
	} else {
		throw new NovaException( L( '_CACHE_TYPE_ILLEGAL_' ), E_ERROR );
	}
	$cache_class = ucwords( $cache_class ) . 'Cache';
	if( class_exists( $cache_class ) ) {
		return new $cache_class( $options );
	} else {
		throw new NovaException( L( '_CACHE_TYPE_ILLEGAL_' ), E_ERROR );
	}
}

// 连接数据库
function connect_database( $type = 'MYSQL' ) {
	$db_class = strtolower( trim( $type ) );
	$db_path = NOVA_CORE . 'database/' . $db_class . '.class.php';
	if( is_file( $db_path ) ) {
		include( $db_path );
	} else {
		throw new NovaException( L( '_DB_TYPE_ILLEGAL_' ), E_ERROR );
	}
	$db_class = ucwords( $db_class ) . 'Database';
	if( class_exists( $db_class ) ) {
		return new $db_class();
	} else {
		throw new NovaException( L( '_DB_TYPE_ILLEAGL_' ), E_ERROR );
	}
}

// 错误输出
function halt( $title, $message, $url = '' ) {
	//[DEBUG]
	global $log;
	//[/DEBUG]
	obclean();
	@header("content-type: text/html; charset=utf-8");
	echo '<html><head><title>' . $title . '</title></head>';
	echo '<body>错误信息：' . $message;
	if( $url != '' ) {
		echo '<br /><br />您可以前往 <a href="' . $url . '">这里</a> 寻求帮助。';
	}
	//[DEBUG]
	if( defined( 'APP_DEBUG' ) && APP_DEBUG === TRUE && defined( 'APP_TRACE' ) && APP_TRACE === TRUE ) {
		echo $log->trace();
	}
	//[/DEBUG]
	echo '</body></html>';
	exit;
}

// 开启输出缓存
function obstart() {
	if ( defined( 'GZIP_ENABLE' ) && GZIP_ENABLE === TRUE && function_exists('ob_gzhandler') ) {
		ob_start('ob_gzhandler');
	} else {
		ob_start();
	}
}
// 清空输出缓存
function obclean() {
	ob_end_clean();
	obstart();
}

// 自动加载
if( !defined( 'APP_DEBUG' ) || APP_DEBUG !== TRUE ) {
	function __autoload( $name ) {
		@header("content-type: text/html; charset=utf-8");
		exit( '<html><head><title>严重的程序错误</title></head><body>由于程序试图使用某些未定义的类，系统被迫中止。</body></html>' );
	}
}

// 浏览器友好的变量输出
function dump( $var, $echo = TRUE, $label = NULL, $strict = TRUE ) {
    $label = ( $label === NULL ) ? '' : rtrim($label) . ' ';
    if( !$strict ) {
        if ( ini_get( 'html_errors' ) ) {
            $output = print_r( $var, TRUE );
            $output = '<pre>' . $label.htmlspecialchars( $output, ENT_QUOTES ) . '</pre>';
        } else {
            $output = $label . " : " . print_r( $var, TRUE );
        }
    }else {
        ob_start();
        var_dump( $var );
        $output = ob_get_clean();
        if( !extension_loaded( 'xdebug' ) ) {
            $output = preg_replace( "/\]\=\>\n(\s+)/m", "] => ", $output );
            $output = '<pre>'. $label . htmlspecialchars( $output, ENT_QUOTES ) . '</pre>';
        }
    }
    if ( $echo ) {
        echo( $output );
        return NULL;
    } else {
        return $output;
    }
}

// 读取目录下的所有子目录
function read_dir( $path ) {
	//[DEBUG]
	global $log;
	//[/DEBUG]
	$dirs = array();
	if( is_dir( $path ) ) {
		if( $d = opendir( $path ) ) {
			while( ($dir = readdir( $d ) ) !== false ) {
				if( is_dir( $path . $dir ) && $dir != '.' && $dir != '..' ) {
					$dirs[] = $path . $dir;
				}
			}
		}
		@closedir( $d );
	//[DEBUG]
	} else {
		if( defined( 'APP_DEBUG' ) && APP_DEBUG === TRUE ) {
    		$log->add( '[' . __FILE__ . '] [' . __LINE__ . '] ' . L( '_USE_ILLEGAL_DIR_NAME_' ) . ' ' . $path, E_USER_NOTICE );
    	}
    //[/DEBUG]
    }
	return $dirs;
}

// 读取目录下的所有文件
function read_file( $directory, $ext = '' ) {
	//[DEBUG]
	global $log;
	//[/DEBUG]
	$files = array();
    if ( is_dir( $directory ) ) {
        $handle = opendir( $directory );
        while ( $file = readdir( $handle ) ){
            $subdir = $directory .$file;
            if ( is_file( $subdir ) ){
            	if( $ext == '' ) {
            		$files[] = $directory . $file;
            	} else {
	                $fileInfo = pathinfo($subdir);
	                $fileExt = $fileInfo['extension'];
	                if ( $fileExt == $ext ){
	                    $files[] = $directory . $file;
	                }
                }
            }
        }
        closedir( $handle );
    //[DEBUG]
    } else {
    	if( defined( 'APP_DEBUG' ) && APP_DEBUG === TRUE ) {
    		$log->add( '[' . __FILE__ . '] [' . __LINE__ . '] ' . L( '_USE_ILLEGAL_DIR_NAME_' ) . ' ' . $directory, E_USER_NOTICE );
    	}
    //[/DEBUG]
    }
    return $files;
}

// 检查错误等级
function check_error_level( $level, $num ) {
	$i = 4096;
	while( $i >= 1 ) {
		if( $level >= $i ) {
			if( $num == $i ) return TRUE;
			$level -= $i;
		}
		$i = $i / 2;
	}
	return FALSE;
}

// 字符串截取
function cut_str( $str, $len = 0, $dot = '...', $encoding = 'utf-8' ) {
	$str = strip_tags( $str );
	if ( !$len || strlen($str) <= $len ) return $str;
	$tempstr = '';
	$str = str_replace('<br />', ' ', $str);
	$str = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $str);
	if ($encoding == 'utf-8') {
		$n = $tn = $noc = 0;
		while($n < strlen($str)) {
			$t = ord($str[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif (194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif (224 <= $t && $t < 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif (240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif (248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif ($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}
			if($noc >= $len) {
				break;
			}
		}
		if($noc > $len) {
			$n -= $tn;
		}
		$tempstr = substr($str, 0, $n);
	} elseif ($encoding == 'gbk') {
		for ($i=0; $i<$len; $i++) {
			$tempstr .= ord($str{$i}) > 127 ? $str{$i}.$str{++$i} : $str{$i};
		}
	}
	$tempstr = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $tempstr);
	return $tempstr.$dot;
}

function php_escape($str) {
	preg_match_all("/[\x80-\xff].|[\x01-\x7f]+/",$str,$r);
	$ar = $r[0];
	foreach($ar as $k=>$v) {
		if(ord($v[0]) < 128)
			$ar[$k] = rawurlencode($v);
		else
			$ar[$k] = "%u".bin2hex(iconv("UTF-8","UCS-2",$v));
	}
	return join("",$ar);
}

function php_unescape($str) {
	$str = rawurldecode($str);
	preg_match_all("/(?:%u.{4})|.+/",$str,$r);
	$ar = $r[0];
	foreach($ar as $k=>$v) {
		if(substr($v,0,2) == "%u" && strlen($v) == 6) {
			$ar[$k] = iconv("UCS-2","UTF-8",pack("H4",substr($v,-4)));
		}
	}
	return join("",$ar);
}

// 检查验证码
function check_verify( $verify ) {
	if( !isset( $_SESSION['vdcode'] ) ) {
		return false;
	}
	if ( strtolower($verify) != $_SESSION['vdcode'] ) {
		return false;
	}
	unset($_SESSION['vdcode']);
	return true;
}

// 生成指定长度的随机字符串
function get_random_string( $len ) {
	$chars = array(
		"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", 
		"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", 
		"w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", 
		"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", 
		"S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", 
		"3", "4", "5", "6", "7", "8", "9");
	$charsLen = count($chars) - 1;

	// 将数组打乱
	shuffle($chars);
    
	$output = "";
	for ($i=0; $i<$len; $i++) {
		$output .= $chars[mt_rand(0, $charsLen)];
	}  
	return $output;
}

function nova_lib( $lib_name ) {
	$file_path = NOVA_LIB . $lib_name . '.class.php';
	return is_file( $file_path ) ? $file_path : NULL;
}

function get_path() {
	$total = $_SERVER['PHP_SELF'];
	$file = explode("/", $total);
	$file = $file[sizeof($file)-1];
	return substr($total,0,strlen($total)-strlen($file)-1);
}




// URL重定向
function redirect( $url, $time=0 ) {
	// redirect
	if( 0 === $time ) {
		header("Location: ".$url);
	} else {
		header("refresh:{$time};url={$url}");
	}
}







// xml编码
function xml_encode($data,$encoding='utf-8',$root="think") {
    $xml = '<?xml version="1.0" encoding="'.$encoding.'"?>';
    $xml.= '<'.$root.'>';
    $xml.= data_to_xml($data);
    $xml.= '</'.$root.'>';
    return $xml;
}

function data_to_xml($data) {
    if(is_object($data)) {
        $data = get_object_vars($data);
    }
    $xml = '';
    foreach($data as $key=>$val) {
        is_numeric($key) && $key="item id=\"$key\"";
        $xml.="<$key>";
        $xml.=(is_array($val)||is_object($val))?data_to_xml($val):$val;
        list($key,)=explode(' ',$key);
        $xml.="</$key>";
    }
    return $xml;
}
?>
